package com.szgd.controller.personnel;

import com.szgd.bean.Attach;
import com.szgd.bean.Health;
import com.szgd.bean.SysDict;
import com.szgd.controller.BaseController;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.personnel.HealthService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.Constant;
import com.szgd.util.ExcelUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.TimeUtil;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/health")
public class HealthController extends BaseController {
    private static Logger logger = Logger.getLogger(HealthController.class);

    @Autowired
    HealthService healthService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    AttachService attachService;

    @RequestMapping(value = "toHealthList", method = RequestMethod.GET)
    public String toHealthList() {
        return "/personnel/health/healthList";
    }

    @RequestMapping(value = "/getHealthList", method = RequestMethod.GET)
    public void  getHealthList(HttpServletResponse response, HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>> dataList = healthService.getHealthList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    @RequestMapping(value = "/healthDetail", method = RequestMethod.GET)
    public ModelAndView trainDetail(
            @RequestParam("id") long id,
            @RequestParam("status") int status,
            ModelAndView modelAndView
    ) throws UnsupportedEncodingException {
        Map<String,Object> healthInfo = healthService.getHealthDetailInfo(id);
        Map<String,Object> healthAttach = healthService.getHealthAttach(id);
        List<SysDict> physicalResultList = sysDictService.getByParentCode("PHYSICAL_RESULT");
        List<SysDict> workTypeList = sysDictService.getByParentCode("WORK_TYPE");
        modelAndView.setViewName("personnel/health/healthDetailInfo");
        modelAndView.addObject("id", id);
        modelAndView.addObject("status", status);
        modelAndView.addObject("health", healthInfo);
        modelAndView.addObject("attach", healthAttach);
        modelAndView.addObject("physicalResultList", physicalResultList);
        modelAndView.addObject("workTypeList", workTypeList);
        return modelAndView;
    }

    @RequestMapping("/saveHealthInfo")
    @ResponseBody
    public Map<String,Object> saveHealthInfo(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> healthAttachMap = (HashMap<String, Object>)paramMap.get("healthAttach");
        String message = "";
        try {
//            List<Map<String, Object>> healthInfoList = healthService.getHealthListNoPage(paramMap);
//            if(healthInfoList != null && healthInfoList.size() > 0){
//                logger.error("保存失败：数据库已存在该员工体检，请勿重复添加");
//                return getErrorMap("保存失败：数据库已存在相同记录，请重新编辑或删除重复记录");
//            }
            paramMap.put("uploader",this.getLoginId(request.getSession()));
            healthService.saveHealthInfo(paramMap);
            try{
                String isHealthAttachChanged = healthAttachMap.get("isHealthAttachChanged").toString();
                if (isHealthAttachChanged.equalsIgnoreCase("1")){
                    healthAttachMap.put("creator",getLoginId(request.getSession()));
                    attachService.saveAttach(healthAttachMap);
                }
            }catch(Exception e){
                e.printStackTrace();
                message = message + ",附件上传失败，请重新编辑此信息再提交";
                logger.error("附件上传失败，请重新编辑此信息再提交:"+e.getMessage());
            }
            if (message.length() > 0 )
                message = "体检信息保存成功!" + " 但" + message;
            else
                message = "体检信息保存成功!";
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("体检信息保存失败："+e.getMessage());
            return getSuccMap("体检信息保存失败："+e.getMessage());
        }
    }

    @RequestMapping("/deleteHealth")
    public void deleteHealth(HttpServletRequest  request, HttpServletResponse response){
        JSONObject json=getJson();
        json.put("success", true);
        json.put("message", "删除成功!");
        try{
            Map<String, Object> params = this.getMapParams(request);
            params.put("userId", this.getLoginId(request.getSession()));
            boolean mark=healthService.deleteHealth(params)>0 ? true : false;
            if(!mark){
                json.put("message", "删除失败!");
            }
        }catch(Exception e){
            logger.error("删除失败！",e);
            json.put("message", "删除失败!");
        }
        outJSONData(response , json);
    }

    @RequestMapping(value = "/toHealthAdd", method = RequestMethod.GET)
    public ModelAndView toTrainAdd(ModelAndView modelAndView) throws UnsupportedEncodingException {
        List<SysDict> physicalResultList = sysDictService.getByParentCode("PHYSICAL_RESULT");
        List<Map<String,Object>> personList = healthService.getAllPerson();
        modelAndView.addObject("physicalResultList", physicalResultList);
        modelAndView.addObject("personList", personList);
        modelAndView.setViewName("personnel/health/healthAdd");
        return modelAndView;
    }

    @RequestMapping(value = "/getPersonnelInfo",method = RequestMethod.GET)
    public void getPersonnelInfo(HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = getJson();
        try {
            Map<String, Object> params = this.getMapParams(request);
            Map<String,Object> res = healthService.getPersonnelInfo(params);

            json.put("res",res);
            json.put("success", true);
            outJSONData(response, json);
        } catch (Exception e) {
            logger.error(e.getMessage());
            json.put("success", false);
            outJSONData(response, json);
        }
    }

    @RequestMapping(value = "/addHealthInfo")
    @ResponseBody
    public Map<String,Object> addHealthInfo(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> healthAttachMap = (HashMap<String, Object>)paramMap.get("healthAttach");
        String message = "";
        boolean isSaveHealth = false;
        try {
            List<Map<String, Object>> healthInfoList = healthService.getHealthListNoPage(paramMap);
            if(healthInfoList != null && healthInfoList.size() > 0){
                logger.error("新增失败：数据库已存在该员工体检，请勿重复添加");
                return getErrorMap("新增失败：数据库已存在该员工体检，请勿重复添加");
            }
            paramMap.put("creator",this.getLoginId(request.getSession()).toString());
            healthService.insertHealthInfo(paramMap);
            isSaveHealth = true;
            healthAttachMap.put("parentId",paramMap.get("id"));
            try{
                String isHealthAttachChanged = healthAttachMap.get("isHealthAttachChanged").toString();
                if (isHealthAttachChanged.equalsIgnoreCase("1") && isSaveHealth){
                    healthAttachMap.put("creator",getLoginId(request.getSession()));
                    attachService.saveAttach(healthAttachMap);
                }
            }catch(Exception e){
                e.printStackTrace();
                message = message + ",附件上传失败，请重新编辑此信息再提交";
                logger.error("附件上传失败，请重新编辑此信息再提交:"+e.getMessage());
            }
            if (message.length() > 0 )
                message = "体检信息新增成功!" + " 但" + message;
            else
                message = "体检信息新增成功!";
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("体检信息新增失败："+e.getMessage());
            return getSuccMap("体检信息新增失败："+e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/batchUploadHealth", method = {RequestMethod.GET, RequestMethod.POST})
    public void batchUploadHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");  //防止ajax接受到的中文信息乱码
        response.setHeader("Content-type", "text/html;charset=UTF-8");   //跟上面同时使用可解决乱码问题
        out = response.getWriter();
        try {
            Map<String, String> fieldMapping = healthService.getFieldMap();
            List<Map<String, Object>> dataList = ExcelUtil.getListByExcel(in, file.getOriginalFilename(), fieldMapping, false);
            String batchNo = TimeUtil.formatDate(Calendar.getInstance().getTime(), "yyyyMMddhhmmss");
            Map<String, Object> resultMap = healthService.batchImportHealth(dataList, this.getLoginId(request.getSession()), batchNo);

            long endTime = System.currentTimeMillis();
            List<Map<String, Object>> successList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_SUCCESS);
            List<Map<String, Object>> ignoreList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_IGNORE);
            List<Map<String, Object>> failedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_FAILED);
            List<Map<String, Object>> updatedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_UPDATED);
            String errorHtml = failedList.size() + "条";

            if (failedList.size() > 0) {
                //生成失败记录文件
                String fileName = "体检列表" + batchNo + ".xls";
                String filePath = PropertiesUtil.get("batchImportErrorPath");
                String realPath = request.getServletContext().getRealPath(filePath);
                filePath = filePath.replace("\\", "/");
                File f = new File(realPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                realPath = realPath + File.separator + fileName;
                exportExcelByTemplate(fieldMapping,failedList, realPath,"体检信息批量导入模版.xls");
                String downloadPath = filePath + "/" + URLEncoder.encode(fileName,"UTF-8");
                errorHtml = "<a href='#WEBROOT#/downloadErrorRecord?path=" + downloadPath + "'>" + failedList.size() + "条（点击查看失败原因）</a>";
            }
            out.print("本次导入共处理" + dataList.size() + "条数据[新增：" + successList.size() + "条，更新："
                    + updatedList.size() + "条，<font color='red'>失败：" + errorHtml
                    + "</font>]，耗时： "
                    + (endTime - startTime) / 1000 + "秒！");
        } catch (Exception e) {
            out.print("文件导入失败！");
            logger.error(e.getMessage());
        }
        out.flush();
        out.close();
    }
}
